package com.webserver.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import com.webserver.http.EmptyRequestException;
import com.webserver.http.HttpContext;
import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.servlet.CreateQRCodeServlet;
import com.webserver.servlet.HttpServlet;
import com.webserver.servlet.LoginServlet;
import com.webserver.servlet.RegServlet;
import com.webserver.servlet.UserListServlet;

/**
 * 该线程用于处理客户端的HTTP交互操作
 * HTTP协议要求客户端与服务端的交互采取"一问一答"。因此这里的处理流程分为三步:
 * 1:解析请求
 * 2:处理请求
 * 3:响应客户端
 * @author pc
 *
 */
public class ClientHandler implements Runnable{
	private Socket socket;
	public ClientHandler(Socket socket) {
		this.socket = socket;
	}
	public void run() {
		try {
			//1解析请求
			//如果实例化HttpRequest抛出EmptyRequestException说明本次是空请求
			HttpRequest request = new HttpRequest(socket);
			HttpResponse response = new HttpResponse(socket);
			
			//2处理请求
			/*
			 * /myweb/reg?username=fancq&password=123456&nickname=fanfan&age=22
			 * 
			 * path:  /myweb/reg
			 */
			String path = request.getRequestURI();
			System.out.println("ClientHandler:抽象路径:"+path);
			
			
			//首先判断该请求是否为请求业务
			HttpServlet servlet = ServerContext.getServlet(path);
			if(servlet != null) {
				servlet.service(request, response);				
			}else {			
				//根据抽象路径，在当前项目目录下寻找该资源
				//                   ./webapps/myweb/index.html
				File file = new File("./webapps"+path);		
				if(file.exists()) {
					System.out.println("该资源已找到！");				
					response.setEntity(file);									
					
				}else {
					System.out.println("该资源不存在!");					
					response.setStatusCode(404);
					response.setStatusReason("NotFound");				
					
					File notFoundPage = new File("./webapps/root/404.html");				
					response.setEntity(notFoundPage);
					
				}
			}
			
			//3响应客户端
			response.flush();
			System.out.println("ClientHandler:响应发送完毕!");
		} catch(EmptyRequestException e) {
			System.out.println("空请求...");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//最终和客户端断开连接
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}











